<template>
	<view>
		<u-field v-model="state.form.phone" label="手机号" placeholder="请输入手机号"> </u-field>
		<u-field v-model="state.form.code" label="验证码" :maxlength="4" placeholder="请输入验证码">
			<template v-slot:right>
				<u-button size="mini" type="success" @click="getCode">{{ codeText }}</u-button>
			</template>
		</u-field>
		<view class="u-padding-top-20">
			<u-button type="primary" shape="circle" @click="login">登录</u-button>
		</view>
		<u-verification-code ref="uCode" @change="codeChange"></u-verification-code>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { sendSmsCode } from '@/api/login';
import { Local } from '@/utils/storage';
import { useUserStore } from '@/stores/user';
const storesUserStore = useUserStore();
const codeText = ref();
const state = reactive<{ form: { phone: string; code: string } }>({
	form: {
		phone: '',
		code: '',
	},
});
const uCode = ref();
const codeChange = (text: string) => {
	codeText.value = text;
};
const getCode = () => {
	if (uCode.value.canGetCode) {
		sendSmsCode(state.form.phone, 'login').then((res) => {
			uni.showToast({
				title: '验证码已发送',
				icon: 'none',
				duration: 3000,
			});
			// 通知验证码组件内部开始倒计时
			uCode.value.start();
		});
	} else {
		uni.$u.toast('倒计时结束后再发送');
	}
};
const login = () => {
	if (!state.form.phone) {
		return uni.$u.toast('请输入手机号');
	}
	if (!uni.$u.test.mobile(state.form.phone)) {
		return uni.$u.toast('手机号格式错误');
	}
	if (!state.form.code) {
		return uni.$u.toast('请输入验证码');
	}
	storesUserStore.phoneLogin(state.form).then((response) => {
		uni.$u.toast('登录成功');
		//获取用户信息
		storesUserStore.getInfo();
		uni.$hxRouter.push({ type: 'reLaunch', url: Local.get('redirectUrl') ? Local.get('redirectUrl') : '/pages/home/index' });
		Local.remove('redirectUrl');
	});
};
</script>

<style></style>
